<template>
	<view>
		<u-form :model="form" label-width="160" ref="uForm">
			<u-form-item label="姓名" left-icon="account" prop="name">
				<u-input v-model="form.name" placeholder="请输入姓名"></u-input>
			</u-form-item>
			<u-form-item label="账号" prop="username" left-icon="man-add">
				<u-input v-model="form.username"></u-input>
			</u-form-item>
			<u-form-item label="密码" prop="password">
				<u-input v-model="form.password" type="password" password-icon></u-input>
			</u-form-item>
			<u-form-item label="确定密码" prop="confirmPassword">
				<u-input v-model="form.confirmPassword"></u-input>
			</u-form-item>
		</u-form>
		<u-button @click="submit">提交</u-button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					name: '',
					username: '',
					password: '',
					confirmPassword: ''
				},
				rules: {
					name: [
						{
							required: true,
							message: '请输入姓名',
							trigger: 'blur'
						}
					],
					username: [
						{
							required: true,
							message: '请输入用户名',
							trigger: 'blur'
						},
						{
							min: 5,
							message: '用户名大小不能小于5个字符',
							trigger: 'change'
						}
					],
					password: [
						{
							required: true,
							message: '请输入密码',
							trigger: 'blur'
						},
						{
							min: 6,
							max:10,
							message: '格式错误',
							trigger: ['change', 'blur']
						}
					],
					confirmPassword: [
						{
							required: true,
							message: '请输入密码',
							trigger: ['change','blur']
						},
						{
							validator: (rule, value, callback) => {
								if(value !== this.form.password){
									callback(new Error('两次密码输入不一致'))
								}else{
									callback()
								}
							},
							trigger: 'change'
						}
					]
				}
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		methods: {
			submit(){
				this.$refs.uForm.validate(valid => {
					if(valid){
					this.register()
					}
				})
			},
			async register(){
				const res = await this.$http({
					url: '/login',
					method: 'POST',
					data: {
						account: this.form.username,
						password: this.form.password
					}
				})
				console.log(res)
				this.$store.commit('user/setToken', res.data.result.token)
			}
		}
	}
</script>

<style lang="scss">
view{
	padding: 20rpx;
	.u-form{
			/deep/.u-form-item--left{
				padding-right: 30rpx;
			}
	}
}
</style>
